package com.cheifsteam.springframework.beans.factory.support;

import com.cheifsteam.springframework.beans.exception.BeansException;
import com.cheifsteam.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author 屈燃希
 * @date 2025/1/20 22:54
 * @content JDK反射实现
 */
public class SimpleInstantiationStrategy  implements InstantiationStrategy{
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor constructor, Object[] args) {
        Class clazz = beanDefinition.getBeanClass();
        try {
            if (constructor != null) {
                return clazz.getDeclaredConstructor(constructor.getParameterTypes()).newInstance(args);
            }
            return clazz.getDeclaredConstructor().newInstance();

        } catch (InstantiationException | NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            throw new BeansException("Failed to instantiate [" + clazz.getName() + "]", e);
        }
    }
}
